<!-- 审计日志 -->
<template>
  <div class="dashboard-editor-container">
		<el-row style="background: #fff; padding: 16px 16px 0;">
      <connsearch ref="connsearch" :formOptions="formOptions"   @search="search" @reset="reset"/>
      <div class="tabclick">
        <!-- <div class="tabitem" @click="handleClick1()">
          <span>显示日统计趋势<i :class="tab1 ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i></span>
        </div> -->
        <div class="tabitem" @click="handleClick()">
          <span><i :class="tab ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i></span>
        </div>
      </div>
      <el-row>
        <el-tabs type="border-card" v-if="tab" style="margin-top:16px;" v-model="activeName" @tab-click="tabClick">
          <el-tab-pane label="显示日统计趋势" name="day" lazy>
            <el-col :xs="24" :sm="24" :lg="24">
              <barchart v-if="this.activeName === 'day'" :chartData="barchartData" @barclick="barclick"/>
            </el-col>
          </el-tab-pane>
          <el-tab-pane label="审计动作统计分析" name="action" lazy>
            <el-row :gutter="20">
              <el-col :xs="24" :sm="24" :lg="24">
                <piechart v-if="this.activeName === 'action'" :title="'审计动作统计分析'" :chartData="pie1Data"  @pieclick="pieclick"/>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="操作用户统计分析" name="user" lazy>
            <el-col :xs="24" :sm="24" :lg="24">
              <piechart v-if="this.activeName === 'user'" :title="'操作用户统计分析'" :chartData="pie4Data"  @pieclick="pieclick"/>
            </el-col>
          </el-tab-pane>
          <el-tab-pane label="严重等级统计分析" name="level" lazy>
            <el-col :xs="24" :sm="24" :lg="24">
              <piechart v-if="this.activeName === 'level'" :title="'严重等级统计分析'" :chartData="pie2Data"  @pieclick="pieclick"/>
            </el-col>
          </el-tab-pane>
          <el-tab-pane label="审计类型统计分析" name="type" lazy>
            <el-col :xs="24" :sm="24" :lg="24">
              <piechart v-if="this.activeName === 'type'" :title="'审计类型统计分析'" :chartData="pie3Data"  @pieclick="pieclick"/>
            </el-col>
          </el-tab-pane>
        </el-tabs>
      </el-row>
      <!-- <barchart /> -->

      <el-col :xs="{ span: 24 }" :sm="{ span: 24 }" :md="{ span: 24 }" :lg="{ span: 24 }" :xl="{ span: 24 }" style="padding-right: 8px;margin: 16px 0;">
        <!-- <span class="title">审计日志列表</span> -->
        <el-table stripe border :data="tableData" style="width: 100%; margin-top: 15px">
          <el-table-column label="序号" width="80" type="index" align="left"></el-table-column>
          <el-table-column label="发生时间" prop="TransTime" align="left" width="160px"></el-table-column>
          <el-table-column label="操作终端" prop="FromIP" align="left" width="160px"></el-table-column>
          <!-- <el-table-column label="审计日志" prop="Operate" align="left" width="250px"></el-table-column> -->
          <!-- <el-table-column label="操作分类" prop="URL" align="left" ></el-table-column> -->
          <el-table-column label="操作用户" prop="UserID" width="120" show-overflow-tooltip align="left"></el-table-column>
          <el-table-column label="审计类型" prop="Type" width="120" show-overflow-tooltip align="left"></el-table-column>
          <el-table-column label="操作命令" prop="CmdCode" width="180" show-overflow-tooltip align="left"></el-table-column>
          <el-table-column label="严重性等级" show-overflow-tooltip align="left" width="120px">
            <template slot-scope="scope">
              <p style="color:red" v-if="scope.row.Level === 1">致命</p>
              <p style="color:#F56C6C" v-if="scope.row.Level === 2">紧急</p>
              <p style="color:#E6A23C" v-if="scope.row.Level === 3">重要</p>
              <p style="color:#E6A23C" v-if="scope.row.Level === 4">监视</p>
              <p style="color:#409EFF" v-if="scope.row.Level === 5">普通</p>
              <p style="color:#67C23A" v-if="scope.row.Level === 6">通知</p>
            </template>
          </el-table-column>
          <el-table-column label="操作结果" show-overflow-tooltip align="left" width="120px">
            <template slot-scope="scope">
              <p style="color:#67C23A" v-if="scope.row.Result === 0">成功</p>
              <p style="color:#909399" v-if="scope.row.Result !=0 ">失败</p>
            </template>
          </el-table-column>
          <el-table-column label="操作描述" prop="Descp" show-overflow-tooltip align="left"></el-table-column>
        </el-table>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page=pageNum
          :page-size=pageSize
          background
          layout="total, prev, pager, sizes, next, jumper"
          :total="total">
        </el-pagination>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getNowDay, parseTime, getTreeData, ParamDictURLtype, classType } from '@/utils/index.js';
import { connrequest } from '@/api/firstPage.js';
import connsearch from "./components/connsearch.vue";
import barchart from "./components/barchart.vue";
import piechart from "./components/piechart.vue";
export default {
  components: { connsearch, barchart, piechart },
  data() {
    let _that = this
    return {
      activeName:'day',
      tableData:[],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      tab: false,
      tab2: false,
      barchartData: {xAxis:[],series:[]},
      pie1Data: [],
      pie2Data: [],
      pie3Data: [],
      pie4Data: [],
      searchform:{},
      formOptions:[
        {
          col: 8,
          label: "日期",
          prop: "timeRange",
          element: "el-date-picker",
          initValue: [],
          type: ""
        },
        {
          col: 8,
          label: "操作结果",
          prop: "Result",
          element: "el-select",
          initValue: 0,
          name:'AuditLogResult',
          options: [],
          events:{
            input (val) {
              // console.log(val);
            }
          }
        },
        {
          col: 8,
          label: "严重等级",
          prop: "Level",
          element: "el-select",
          initValue: 0,
          placeholder: "请选择审计结果",
          options:[],
          name:'AuditLogLevel',
          events:{
            input (val) {
              // console.log(val)
            }
          }
        },
        {
          col: 8,
          label: "审计类型",
          prop: "Type",
          element: "el-select",
          initValue: 0,
          options: [],
          name:'AuditLogType',
          events:{
            input (val) {
              // // console.log(val);
              _that.getAuditFilterInfo(val);
              _that.$refs.connsearch.searchform.CmdCode = 0;
            }
          }
        },
        {
          col: 8,
          label: "操作命令",
          prop: "CmdCode",
          element: "el-select",
          initValue: 0,
          name:'',
          options: [],
          events:{
            input (val) {
              // this.getAuditFilterInfo(val);
              // console.log(val);
            }
          }
        }
      ]
    };
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.pageSize = this.$store.state.user.DefaultPageLength;
    let xTime = new Date().getTime()
    // let endTime = new Date().getTime()
    let endTime = new Date(new Date().setHours(0, 0, 0, 0))
    let startTime = endTime - ( this.$store.state.user.DefaultLogDays * 24 * 60 * 60 *1000);
    
    let arr = [ parseTime(startTime), '']
    this.formOptions.map( item => {
      if(item.label === '日期'){
        item.initValue = arr
      }
    })
    this.$set(this.searchform,'timeRange', arr)
    this.$set(this.searchform,'Result', 0)
    this.$set(this.searchform,'CmdCode', 0)
    this.$set(this.searchform,'Level', 0)
    this.$set(this.searchform,'Type', 0)
    this.getData()
    this.GetEmployee()
    this.GetUIDictParam('')
    this.GetAuditLogSumByDate()
    // this.GetParamDictURL()
    this.getAuditFilterInfo(0)
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
  },
  methods:{
    getData(){
      // this.getAuditTypeList(); //获取审计类型
      this.GetAuditLog() //列表数据
      // this.GetAuditLogSumByUser(); //操作用户统计
      // this.GetAuditLogSumByCommandCode();//审计动作统计
      // this.GetShadowURLSumGroupByURL()
      // this.GetAuditLogSumByLevel() //严重等级统计
      // this.GetShadowURLSumGroupBySubClass()
      // this.GetAuditLogSumByDate() //日期统计
      // this.GetAuditLogSumByType() //审计类型统计
    },
    async GetUIDictParam(type){
      
      const data = {
        Data : {
          FilterType:type
        }
      }
      let options = []
      // let FileAcitonOption = []
      const res = await connrequest('GetUIDictParam',data)
      console.log(res);
      let arr = [{value: 0, label: '全部'}]
      if (type === '') {
        this.formOptions.map( item => {
          item.options = [{value: 0, label: '全部'}]
          for (const key in res.Data) {
            if(item.name === key){
              res.Data[key].map(items=>{
                item.options.push({
                  label:items.Descp,
                  value:items.Value
                })
              })
            }
          }
          console.log(options);
        })
        
      } else {
        
      }
      
    },
    tabClick(tab){
      // this.reset()
      if(tab.name === 'day'){
        this.GetAuditLogSumByDate()
      }else if(tab.name === 'action'){
        this.GetAuditLogSumByCommandCode();
      }else if(tab.name === 'user'){
        this.GetAuditLogSumByUser();
      }else if(tab.name === 'level'){
        this.GetAuditLogSumByLevel()
      }else if(tab.name === 'type'){
        this.GetAuditLogSumByType()
      }
    },
    barclick(val){
      this.pageNum = 1
      this.searchform.timeRange = [ `${val} 00:00:00`, `${val} 23:59:59` ]
      this.GetAuditLog()
    },
    pieclick(val, title, id){
      this.pageNum = 1
      if(title === '按终端用户统计'){
        this.searchform.Name = val
      }else if(title === '操作用户统计分析'){
        this.searchform.UserID = val
      }else if(title === '严重等级统计分析'){
        this.searchform.Level = id
        this.$refs.connsearch.searchform.Level = id
      }else if(title === '审计动作统计分析'){
        this.searchform.CmdCode = id
        this.$refs.connsearch.searchform.CmdCode = id
      }else if(title === '审计类型统计分析'){
        this.searchform.Type = id
        this.$refs.connsearch.searchform.Type = id
      }
      this.GetAuditLog()
    },
    // 获取审计类型下拉框数据
    async getAuditTypeList(){
      let option = []
      const res = await connrequest('GetAuditTypeList')
      let arr = [{value: 0, label: '全部'}]
      this.formOptions.map( item => {
        if(item.label === '审计类型'){
          res.Data.map(items=>{
            option.push({
              label:items.Descp,
              value:items.Value
            })
          })
          item.options = [...arr,...option]
        }
      })
    },
    async getAuditFilterInfo(type){
      const data={
        Data:{
          Type:type
        }
      }
      const res = await connrequest('GetAuditFilterInfo',data)
      res.Data = res.Data.CmdCode.map(item => {
        item.label = item.Descp
        item.value = item.CmdCode
        return item
      })
      let arr = [{value: 0, label: '全部'}]
      this.formOptions.map( item => {
        if(item.label === '操作命令'){
          item.options = [...arr,...res.Data]
        }
        // console.log(item.label);

      })
    },
    // 操作命令转换
    async filterCodCode(ClassID){
      const data={
        Data:{
          Type:0
        }
      }
      let Name = ''
      const res = await connrequest('GetAuditFilterInfo',data)
      res.Data = res.Data.CmdCode.map(item => {
        if (item.CmdCode === ClassID) {
          Name = item.Descp;
        }
      })
      return Name
    },
    // 获取终端用户
    async GetEmployee(){
      const res = await connrequest('GetEmployee')
      res.Data = res.Data.map(item => {
        item.label = item.Department +' / '+item.Name 
        item.value = item.Name
        return item
      })
      let arr = [{value: '', label: '全部'}]
      this.formOptions.map( item => {
        if(item.label === '终端用户'){
          item.options = [...arr,...res.Data]
        }
      })
    },
    // 获取域名分类
    async GetParamDictURL(){
      const res = await connrequest('GetParamDictURL')
      this.Options = res.Data
      let arr = []
      let idlist = []
      res.data = res.Data.map(item => {
        arr.push(item.MainClass)
        idlist.push(item.MainID)
      })
      arr = Array.from(new Set(arr))
      idlist = Array.from(new Set(idlist))
      // 给原数组加根节点
      arr.map((item,index) => {
        res.Data.push({ClassID: 0, MainID: idlist[index], MainClass: "根节点", SubClass: item, CreateEvent: 0})
      })
      this.formOptions.map( item => {
        if(item.label === '域名分类'){
          item.options = getTreeData(this.treeing(res.Data))
        }
      })
    },
    treeing(arr) {
      let res = [] // 存放结果集
      let map = {}
      // 判断对象是否有某个属性
      let getHasOwnProperty = (obj, property) => Object.prototype.hasOwnProperty.call(obj, property)
      // 边做map存储，边找对应关系
      for (const i of arr) {
        map[i.SubClass] = {
            ...i,
            children: getHasOwnProperty(map, i.SubClass) ? map[i.SubClass].children : []
        }
        const newItem = map[i.SubClass]
        if (i.MainClass === '根节点') {
          res.push(newItem)
        } else {
          if (!getHasOwnProperty(map, i.MainClass)) {
            map[i.MainClass] = {
              children: []
            }
          }
          map[i.MainClass].children.push(newItem)
        }
      }
      return res
    },
    // 获取事件日期统计
    async GetAuditLogSumByDate() {
      let xAxis = []
      let series= []
      const data = {
        Filter:{
          StartTime: this.searchform.timeRange?.[0] ||  getNowDay('time'),
          EndTime: this.searchform.timeRange?.[1] || '',
          Name:'',
          Descp: this.searchform.URL || '',
          SumCount: 0
        }
      }
      const res = await connrequest('GetAuditLogSumByDate', data)
      res.Data.map( item =>{
        xAxis.push(item.Date)
        series.push(item.Count)
      })
      this.barchartData = {xAxis,series}
    },
    // 获取审计动作统计
    async GetAuditLogSumByCommandCode(){
      let arr = []
      const data = {
        Filter:{
          StartTime: this.searchform.timeRange?.[0] ||  getNowDay('time'),
          EndTime: this.searchform.timeRange?.[1] || '',
          TransDate: '',
          Result: this.searchform.Result,
          CmdCode: this.searchform.CmdCode,
          Level: this.searchform.Level,
          UserID:'',
          Descp:'',
          SumCount: 0
        }
      }
      const res = await connrequest('GetAuditLogSumByCommandCode', data)
      res.Data.map( item =>{
        this.formOptions.map( formItem => {
          if(formItem.label === '操作命令'){
            formItem.options.map( newitem =>{
                if(item.ClassID === newitem.value){
                  // console.log(111111);
                  item.Name = newitem.label
                }
            })
          }
        })
        arr.push({name: item.Name, id: item.ClassID, value: item.Count})
      })
      // res.Data.map( item =>{
      //   // console.log(this.filterCodCode(item.ClassID));
      //   arr.push({name: item.Descp, value: item.Count,id:item.CmdCode})
      // })
      this.pie1Data = arr
    },
    // 获取审计用户统计
    async GetAuditLogSumByUser(){
      let arr = []
      const data = {
        Filter:{
          StartTime: this.searchform.timeRange?.[0] ||  getNowDay('time'),
          EndTime: this.searchform.timeRange?.[1] || '',
          TransDate: '',
          Result: this.searchform.Result,
          CmdCode: this.searchform.CmdCode,
          Level: this.searchform.Level,
          UserID:'',
          Descp:'',
          SumCount: 0
        }
      }
      const res = await connrequest('GetAuditLogSumByUser', data)
      res.Data.map( item =>{
        arr.push({name: item.Name, value: item.Count})
      })
      this.pie4Data = arr
    },
    // 获取严重等级统计
    async GetAuditLogSumByLevel(){
      let arr = []
      const data = {
        Filter:{
          StartTime: this.searchform.timeRange?.[0] ||  getNowDay('time'),
          EndTime: this.searchform.timeRange?.[1] || '',
          TransDate:'',
          Result:this.searchform.Result,
          CmdCode: this.searchform.CmdCode,
          Level:this.searchform.Level,
          Type:this.searchform.Type,
          Descp:'',
          SumCount: 0
        }
      }
      const res = await connrequest('GetAuditLogSumByLevel', data)
      res.Data.map( item =>{
        // console.log(item);
        arr.push({name: classType(item.ClassID), value: item.Count,id:item.ClassID})
      })
      this.pie2Data = arr
    },
    // 获取域名小类统计
    async GetAuditLogSumByType(){
      let arr = []
      const data = {
        Filter:{
          StartTime: this.searchform.timeRange?.[0] ||  getNowDay('time'),
          EndTime: this.searchform.timeRange?.[1] || '',
          TransDate:'',
          Result:this.searchform.Result,
          CmdCode: this.searchform.CmdCode,
          Level: this.searchform.Level,
          Type: this.searchform.Type,
          Name:'',
          Descp:'',
          SumCount: 0
        }
      }
      const res = await connrequest('GetAuditLogSumByType', data)
      res.Data.map( item =>{
        this.formOptions.map( formItem => {
          if(formItem.label === '审计类型'){
            formItem.options.map( newitem =>{
                if(item.ClassID === newitem.value){
                  // console.log(111111);
                  item.Name = newitem.label
                }
            })
          }
        })
        arr.push({name: item.Name, id: item.ClassID, value: item.Count})
      })
      // res.Data.map( item =>{
      //   arr.push({name: item.ClassID, value: item.Count, id: item.ClassID})
      // })
      this.pie3Data = arr
    },
    // 获取审计域名统计
    async GetShadowURLSumGroupByURL(){
      let arr = []
      const data = {
        Filter:{
          StartTime: this.searchform.timeRange?.[0] ||  getNowDay('time'),
          EndTime: this.searchform.timeRange?.[1] || '',
          Name:this.searchform.Name || '',
          Descp: this.searchform.URL || '',
          SumCount: 10
        }
      }
      const res = await connrequest('GetShadowURLSumGroupByURL', data)
      res.Data.map( item =>{
        arr.push({name: item.URL, value: item.Count})
      })
      this.pie4Data = arr
    },
    // 获取审计日志列表
    async GetAuditLog(){
      let arr
      if(this.searchform?.type?.length > 0){
        let subClass = this.searchform?.type[this.searchform?.type?.length - 1]
        arr = this.Options.filter(item => {return item.SubClass === subClass})
      }
      const data = {
        Paging: {
          QueryPageNo: this.pageNum,
          QueryPageLength: this.pageSize
        },
        Filter: {
          StartTime: this.searchform.timeRange?.[0] ||  getNowDay('time'),
          EndTime: this.searchform.timeRange?.[1] || '',
          TransDate: '',
          UserID:this.searchform.UserID,
          Type:this.searchform.Type,
          Result: this.searchform.Result,
          CmdCode: this.searchform.CmdCode,
          Level:  this.searchform.Level
        }
      }
      const res = await connrequest('GetAuditLog', data)
      // res.Data.map( item =>{
      //   item.ClassID = ParamDictURLtype(item.ClassID)
      //   item.TransTime = parseTime(item.TransTime, '{y}-{m}-{d} {h}:{i}:{s}')
      //   item.AccessType = item.AccessType === 1 ? '禁止' : (item.AccessType === 2 ? '加速' : '直连')
      // })
      this.tableData = res.Data
      this.total = res.Paging.TotalCount
    },
    handleSizeChange(val){
      this.pageNum = 1
      this.pageSize = val
      this.GetAuditLog()
    },
    handleCurrentChange( pageNum ){
      this.pageNum = pageNum
      this.GetAuditLog()
    },
    search(val) {
      this.pageNum = 1
      this.searchform = {...val}
      this.getData()
      if(this.activeName === 'day'){
        this.GetAuditLogSumByDate()
      }else if(this.activeName === 'action'){
        this.GetAuditLogSumByCommandCode();
      }else if(this.activeName === 'user'){
        this.GetAuditLogSumByUser();
      }else if(this.activeName === 'level'){
        this.GetAuditLogSumByLevel()
      }else if(this.activeName === 'type'){
        this.GetAuditLogSumByType()
      }
    },
    reset() {
      let xTime = new Date().getTime()
      let endTime = new Date(new Date().setHours(0, 0, 0, 0))
      let startTime = endTime - (window.sessionStorage.getItem('DefaultLogDays') * 1 * 3600 * 24 * 1000);
      let arr = [ parseTime(startTime), '']
      this.pageNum = 1
      this.formOptions = this.formOptions.map( item => {
        if(item.label === "域名分类" || item.label === "日期"){
          item.initValue = arr
        }else if(item.label === "统计排名"){
          item.initValue = 10
        }else if(item.label === "审计结果"){
          item.initValue = 0
        }else{
          item.initValue = ""
        }
        return item
      })
      this.searchform = {}
      this.$set(this.searchform,'timeRange', arr)
      this.$set(this.searchform,'Result', 0)
      this.$set(this.searchform,'CmdCode', 0)
      this.$set(this.searchform,'Level', 0)
      this.$set(this.searchform,'Type', 0)
      this.$refs.connsearch.addInitValue()
      this.getData()
    },
    handleClick() {
      this.tab = !this.tab
    },
    handleClick2() {
      this.tab2 = !this.tab2
    }
  }
};
</script>
<style lang="scss" scoped>
@import "~@/styles/variables.scss";
@import "./components/css/conncss.scss";
</style>
